﻿using System;
using Microsoft.Xna.Framework;

namespace Library
{
    public class Camera :Component, I3DComponent
    {
        Vector3 pos = Vector3.Zero;
        Matrix rotMatrix = Matrix.Identity;
        Vector3 target = new Vector3(0, 0, -1);
        Vector3 up = Vector3.Up;
        Matrix view;
        Matrix projec;

        public virtual Vector3 Target
        {
            get { return target; }
            set { target = value; }
        }

        public virtual Matrix View
        {
            get { return view; }
            set { view = value; }
        }

        public virtual Matrix Projection
        {
            get { return projec; }
            set { projec = value; }
        }

        public virtual Vector3 Up
        {
            get { return up; }
            set { up = value; }
        }

        public virtual Vector3 Position
        {
            get { return pos; }
            set { pos = value; }
        }

        public virtual Vector3 Scale
        {
            get { return Vector3.One; }set { }
        }

        public Vector3 EulRotation
        {
            get { return MathUtils.MatrixToVector3(Rotation); }
            set { Rotation = MathUtils.Vector3ToMatrix(value); }
        }

        public virtual BoundingBox BoundingBox
        { get { return new BoundingBox(Position - Vector3.One,Position + Vector3.One);  }}
        public virtual Matrix Rotation
        {
            get { return rotMatrix; }
            set { rotMatrix = value; }
        }

        public Camera(Screen Parent) :base(Parent){}
        public Camera() : base(){}

        public override void Draw()
        {
            Vector3 newFor = Target - Position;
            newFor.Normalize();

            Matrix rotMatrixCopy = this.Rotation;
            rotMatrixCopy.Forward = newFor;

            Vector3 referenceVector = Vector3.Up;
            if (rotMatrixCopy.Forward.Y == referenceVector.Y
                || rotMatrixCopy.Forward.Y == -referenceVector.Y)
                referenceVector = Vector3.Backward;

            rotMatrixCopy.Right = Vector3.Cross(this.Rotation.Forward, referenceVector);
            rotMatrixCopy.Up = Vector3.Cross(this.Rotation.Right, this.Rotation.Forward);
            this.Rotation = rotMatrixCopy;
            Up = Rotation.Up;
            view = Matrix.CreateLookAt(Position, Target, Up);
            Projection = MathUtils.CreateProjectionMatrix();
        }
    }
}
